package com.mouse.remind;

import java.lang.reflect.Field;
import java.util.Calendar;


import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.DatePicker;


/**
 * 修复bug的dialog类，提供与DatePickerDialog一样的方法
 * 
 * @version 1.0
 *
 */
public class FixedDatePickerDialog extends DatePickerDialog {
	  public FixedDatePickerDialog(Context context, OnDateSetListener callBack,
			int year, int monthOfYear, int dayOfMonth) {
		super(context, null, year, monthOfYear, dayOfMonth);
		initializePicker(callBack);
	}

	//I use a Calendar object to initialize it, but you can revert to Y,M,D easily
	  public FixedDatePickerDialog(Calendar dateToShow, Context context, OnDateSetListener callBack) {
	    super(context, null, dateToShow.get(Calendar.YEAR), dateToShow.get(Calendar.MONTH), dateToShow.get(Calendar.DAY_OF_MONTH));
	    initializePicker(callBack);
	  }

	  public FixedDatePickerDialog(Calendar dateToShow, Context context, int theme,
	    OnDateSetListener callBack) {
	    super(context, theme, null, dateToShow.get(Calendar.YEAR), dateToShow.get(Calendar.MONTH), dateToShow.get(Calendar.DAY_OF_MONTH));
	    initializePicker(callBack);
	  }

	  private void initializePicker(final OnDateSetListener callback) {
	    try {
	      //If you're only using Honeycomb+ then you can just call getDatePicker() instead of using reflection
	      Field pickerField = DatePickerDialog.class.getDeclaredField("mDatePicker");
	      pickerField.setAccessible(true);
	      final DatePicker picker = (DatePicker) pickerField.get(this);
	      this.setCancelable(true);
	      this.setButton(DialogInterface.BUTTON_NEGATIVE, getContext().getText(android.R.string.cancel), (OnClickListener) null);
	      this.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getText(android.R.string.ok),
	          new DialogInterface.OnClickListener() {
	              @Override
	              public void onClick(DialogInterface dialog, int which) {
	                picker.clearFocus(); //Focus must be cleared so the value change listener is called
	                callback.onDateSet(picker, picker.getYear(), picker.getMonth(), picker.getDayOfMonth());
	              }
	          });
	    } catch (Exception e) { /* Reflection probably failed*/ }
	  }
	}